#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "calc.h"

int main(int argc, char *argv[])
{
  int type;
  double op1, op2;
  char s[MAXOP];

  while ((type = getop(s)) != QUIT) {
    printf("%s: getop type: %s\n", __func__, getoperate(type));
    switch (type) {
      case VAR:
        push(get_var(s));
        /* push(value); */
        break;
      case NUMBER:
        push(atof(s));
        break;
      case PLUS:
        push(pop() + pop());
        break;
      case MULTI:
        push(pop() * pop());
        break;
      case MINUS:
        op2 = pop();
        op1 = pop();
        printf("%s: MINUS %g - %g\n", __func__, op1, op2);
        push(op1 - op2);
        break;
      case DIVIDE:
        op2 = pop();
        if (op2 != 0)
          push(pop() / op2);
        else {
          ERROR("error: zero divisor\n");
          return -1;
        }
        break;
      case MOD:
        op2 = pop();
        op1 = pop();
        if (op1 - (int)op1 == 0 && op2 - (int)op2 == 0)
          push((int)op1 % (int)op2);
        else {
          ERROR("err: %% can't use with %g, %g\n", op1, op2);
          return -1;
        }
        break;
      case SIN:
        push(sin(pop()));
        break;
      case EXP:
        push(exp(pop()));
        break;
      case POW:
        op2 = pop();
        push(pow(pop(), op2));
        break;
      case EQ:
          printf("\t%.8g\n", pop());
        break;
      case SET:
        printf("case SET\n");
        if (pop() == SET) {
          value = get_top_stack();
          set_var(name, get_top_stack());
        } else {
          ERROR("err: no variable set!\n");
          return -1;
        }
        break;
      default:
        strncpy(name, s, strlen(s));
        push(SET);
        printf("defalut command %s\n", s);
        break;
    }
  }
  free_var();
  return 0;
}
